import {
  reqCategory1Data,
  reqCategory2Data,
  reqCategory3Data,
} from "@/api/product/attr";
import { createSlice } from "@reduxjs/toolkit";

const category = createSlice({
  name: "category",
  initialState: {
    category1List: [],
    category2List: [],
    category3List: [],
    category1Id: 0,
    category2Id: 0,
    category3Id: 0,
    category1Name: "",
    category2Name: "",
    category3Name: "",
  },
  reducers: {
    saveCategory1(state, action) {
      state.category1List = action.payload;
    },
    saveCategory2(state, action) {
      state.category2List = action.payload;
    },
    saveCategory3(state, action) {
      state.category3List = action.payload;
    },
    setCategory1Id(state, { payload }) {
      state.category1Id = payload;
    },
    setCategory2Id(state, { payload }) {
      state.category2Id = payload;
    },
    setCategory3Id(state, { payload }) {
      state.category3Id = payload;
    },
    setCategory1Name(state, { payload }) {
      state.category1Name = payload;
    },
    setCategory2Name(state, { payload }) {
      state.category2Name = payload;
    },
    setCategory3Name(state, { payload }) {
      state.category3Name = payload;
    },
  },
});

//提取action方法
export const {
  saveCategory1,
  saveCategory2,
  saveCategory3,
  setCategory1Id,
  setCategory1Name,
  setCategory2Id,
  setCategory2Name,
  setCategory3Id,
  setCategory3Name,
} = category.actions;

//获取一级分类数据
export const getCategory1List = (): any => {
  return async (dispatch: any) => {
    const res = await reqCategory1Data();
    console.log(res);

    dispatch(saveCategory1(res));
  };
};
//获取二级分类
export const getCategory2List = (id: number): any => {
  return async (dispatch: any) => {
    const res = await reqCategory2Data(id);
    dispatch(saveCategory2(res));
  };
};

//获取三级分类
export const getCategory3List = (id: number): any => {
  return async (dispatch: any) => {
    const res = await reqCategory3Data(id);
    dispatch(saveCategory3(res));
  };
};

export default category.reducer;
